package luogu;

import java.math.BigInteger;
import java.util.Scanner;

public class Main1591 {

        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int t = scanner.nextInt();

            for (int i = 0; i < t; i++) {
                int n = scanner.nextInt();
                int a = scanner.nextInt();
                BigInteger factorial = BigInteger.ONE;

                // 计算n的阶乘
                for (int j = 2; j <= n; j++) {
                    factorial = factorial.multiply(BigInteger.valueOf(j));
                }

                // 将阶乘结果转换为字符串
                String factorialStr = factorial.toString();
                int count = 0;

                // 统计数码a出现的次数
                for (int k = 0; k < factorialStr.length(); k++) {
                    if (factorialStr.charAt(k) - '0' == a) {
                        count++;
                    }
                }

                // 输出当前组的结果
                System.out.println(count);
            }
        }
    }

